package helper

import (
	"fmt"
	"gin-ranking/common/util"
	"gin-ranking/common/zinx/tcp/lock/helper"
	"gin-ranking/common/zinx/tcp/lock/iService"
	"gin-ranking/common/zinx/tcp/lock/lockMessage"
	"gin-ranking/common/zinx/tcp/lock/serviceImpl"
	"gin-ranking/common/zinx/ziface"
	"gin-ranking/common/zinx/znet"
	"strconv"
)

// ProcessLockMessageHandler 消息处理器
func ProcessLockMessageHandler(handler iService.ILockMessage, message lockMessage.TcpMessage) lockMessage.TcpMessage {

	if message.DataByes == nil {
		return lockMessage.TcpMessage{}
	}

	// 填充锁密钥
	helper.FillLockKey(&message)

	// 数据块(解密后的原始业务数据块)
	OriginBizDataBytes := util.ResponseBizDecryptBytes(message.EncryptType, message.LockId, message.DataByes)
	message.OriginBizDataBytes = OriginBizDataBytes

	// 校验签名
	if handler.CheckMd5Sign(message) == false {
		return lockMessage.TcpMessage{}
	}

	// 处理业务数据
	return handler.Handler(message)
}

// GetLockMessageService 获取解析的实现类型
func GetLockMessageService(actionCode int) iService.ILockMessage {

	switch actionCode {
	case helper.LockActionCode0X1010.Action:
		return serviceImpl.Lock1010AwakeHandler{}
	}
	return nil
}

// ReceiveDataBytes 接受数据
func ReceiveDataBytes(request ziface.IRequest, bytes []byte) {

	conn := request.GetConnection()
	connId := strconv.Itoa(int(conn.GetConnID()))

	cacheBuf := helper.GetByteBufCache(connId)

	// 全部读出，写入缓存ByteBuf
	err := cacheBuf.WriteBytes(bytes)
	if err != nil {
		fmt.Println("write bytes err:", err)
		panic("write bytes err:" + err.Error())
	}

	for {
		// 判断是否包含 包头索引值
		beginBeforeIndex := lockMessage.IndexOf(cacheBuf, lockMessage.GetBeginDelimiter())

		// 添加缓存
		helper.SetByteBufCache(connId, *cacheBuf)
		if beginBeforeIndex < 0 {
			break
		}
		// 开始解码
		msg := lockMessage.DecoderMsg(cacheBuf)

		// 添加缓存
		helper.SetByteBufCache(connId, *cacheBuf)

		if len(msg.DataByes) < 0 {
			break
		}

		// 传递 message 并解析数据
		service := GetLockMessageService(int(msg.ActionCode))

		if service != nil {
			returnMessage := ProcessLockMessageHandler(service, msg)

			if returnMessage.ActionCode > 0 {
				returnBytes := lockMessage.Encoder(returnMessage)
				if err := conn.SendMsg(returnBytes); err != nil {
					fmt.Println("err =", err)
				}
			} else {
				fmt.Println("message err =", returnMessage)
			}

		}
	}
}

// PingRouter ping test 自定义路由
type PingRouter struct {
	znet.BaseRouter
}

// Handle Test
func (p *PingRouter) Handle(request ziface.IRequest) {

	// 读取客户端数据，写回 ping..ping
	fmt.Println("receive from client:, data = ", request.GetData())
	ReceiveDataBytes(request, request.GetData())

	//hex := "11"
	//bytes := util.HexToBytes(hex)
	//
	//if err := request.GetConnection().SendMsg(bytes); err != nil {
	//	fmt.Println("err =", err)
	//}
}
